import _ from 'lodash'
import { onMounted, onBeforeUnmount } from 'vue'
import type { Ref } from 'vue'

export default function useCalculatePageSize(
  tableModuleRef: Ref<InstanceType<typeof HTMLElement>>,
  pageSize: Ref<number>
) {
  // 获取 PageSize
  const getPageSize = _.debounce(function () {
    const bodyWrapperEl = tableModuleRef.value.querySelector(
      '.el-table__body-wrapper'
    )

    // 默认展示 10 条数据
    if (!bodyWrapperEl) {
      pageSize.value = 10
      return
    }

    const clientHeight = bodyWrapperEl.clientHeight
    // table 一行元素高度约为 50px
    pageSize.value = Math.ceil(clientHeight / 50)
  }, 150)

  onMounted(() => {
    getPageSize()
    window.addEventListener('resize', getPageSize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', getPageSize)
  })
}
